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KEY-----`

export default function Encryption(str, type) {
  if (type === 1) {
    /**RSA加密（公钥）*/
    try {
      // 初始化加密器
      const encrypt = new JSEncrypt()

      // 设置公钥
      encrypt.setPublicKey(`-----BEGIN PUBLIC KEY-----${appid}-----END PUBLIC KEY-----`)

      // 确保输入是字符串
      const inputStr = String(str)

      // 按245字节分块（与PHP端保持一致）
      const chunks = []
      for (let i = 0; i < inputStr.length; i += 245) {
        chunks.push(inputStr.substr(i, 245))
      }

      // 加密每个块并进行base64编码
      const encryptedChunks = chunks.map((chunk) => {
        const encryptedData = encrypt.encrypt(chunk)
        if (!encryptedData) {
          throw new Error('Encryption failed for chunk')
        }
        // JSEncrypt.encrypt 已经做了 base64 编码，所以不需要额外编码
        return encryptedData
      })

      // 用 | 连接加密块
      return encryptedChunks.join('|')
    } catch (error) {
      console.error('加密错误:', error)
      return null
    }
  } else {
    /**RSA解密（私钥）*/
    try {
      if (!str) {
        return null
      }

      // 清理输入字符串
      str = str.replace(/^['"]|['"]$/g, '').trim()
      str = str.replace(/ /g, '+') // 修复可能的base64 '+'号问题

      // 初始化解密器
      const decrypt = new JSEncrypt()

      // 设置私钥
      decrypt.setPrivateKey(
        `-----BEGIN RSA PRIVATE KEY-----\n${appkey}\n-----END RSA PRIVATE KEY-----`
      )

      // 分割加密块
      const chunks = str.split('|')

      // 如果没有分块，直接解密整个字符串
      if (chunks.length === 1) {
        const decrypted = decrypt.decrypt(str)
        return decrypted || null
      }

      // 如果有分块，解密每个块
      let result = ''
      for (const chunk of chunks) {
        const decrypted = decrypt.decrypt(chunk)
        if (decrypted) {
          result += decrypted
        }
      }

      return result || null
    } catch (error) {
      console.error('解密错误:', error)
      return null
    }
  }
}
